package xyz.eden.boot.common.web.support.infrastructure.resource.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import xyz.eden.boot.common.web.support.infrastructure.resource.db.po.BasePO;
import xyz.eden.boot.common.web.support.infrastructure.resource.service.param.BaseQryParam;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * BaseQueryResource
 *
 * @author gavin
 * @version 1.0
 * @descriptor
 * @date 2023/3/2 11:38
 */
public interface BaseQueryResource<PO extends BasePO, QryParam extends BaseQryParam> extends IService<PO> {

    default PO getInfoById(Long id) {
        if (Objects.isNull(id)) {
            return null;
        }

        BaseMapper<PO> baseMapper = this.getBaseMapper();
        return baseMapper.selectById(id);
    }

    /**
     * get page list by param
     *
     * @param offset
     * @param limit
     * @param qryParam
     * @return
     */
    default Page<PO> getListByPage(int offset, int limit, QryParam qryParam) {
        /**
         * 1. 构建查询条件
         */
        LambdaQueryWrapper<PO> queryWrapper = this.builderPageQueryWrapper(qryParam);
        if (Objects.isNull(queryWrapper)) {
            return new Page<>(offset, limit);
        }

        /**
         * 2. 查询数据
         */
        Page<PO> page = PageHelper.offsetPage(offset, limit, true);
        BaseMapper<PO> baseMapper = this.getBaseMapper();
        baseMapper.selectList(queryWrapper);
        return page;
    }

    /**
     * get list by param
     *
     * @param qryParam
     * @return
     */
    default List<PO> getListByParam(QryParam qryParam) {
        /**
         * 1. 构建查询条件
         */
        LambdaQueryWrapper<PO> queryWrapper = this.builderPageQueryWrapper(qryParam);
        if (Objects.isNull(queryWrapper)) {
            return Collections.emptyList();
        }

        /**
         * 2. 查询数据
         */
        BaseMapper<PO> baseMapper = this.getBaseMapper();
        return baseMapper.selectList(queryWrapper);
    }

    LambdaQueryWrapper<PO> builderPageQueryWrapper(QryParam qryParam);
}
